import React, {Component} from 'react';
import {Table, Button, Pagination, Message, Notification, Input, Form, MessageBox, Dialog, Select} from 'element-react';
import axios from "axios";
import { createStore } from 'redux';
import reducer from '../../reducer';
// import actions from '../../action'



const store = createStore(reducer);

class HomePage extends Component {
  constructor(props) {
    super(props);
    var haha = this;
    this.state = {
      columns: [
        {
          label: "id",
          prop: "id",
        },
        {
          label: "姓名",
          prop: "name",
        },
        {
          label: "性别",
          prop: "sex",
          width: 80
        },
        {
          label: "介绍",
          prop: "intro"
        },
        {
          label: "身高",
          prop: "stature"
        },
        {
          label: "创建时间",
          prop: "createtime",
          render: (data) => {
            return (
            <span>{this.formatDate(data.createtime)}</span>
            )
          }
        },
        {
          label: "修改时间",
          prop: "updatedtime",
          render: (data) => {
            return (
                <span>{this.formatDate(data.updatedtime)}</span>
            )
          }
        },
        {
          label: "操作",
          render: (row) => {
            return (
                <span>
                  <Button type="text" size="small" onClick={this.editData.bind(this,row)}>编辑</Button>
                  <Button type="text" size="small" onClick={this.delData.bind(this,row)}>移除</Button>
                </span>
              )
          }
        }

      ],
      data: [],
      count: 0,
      total: 0,
      currentPage: 1,
      pageSize: 10,
      labelPosition: 'right',
      form: {
        name: '',
        sex: '',
        intro: '',
        stature: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'blur,change' }
        ],
        intro: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],
        stature: [
          { required: true, message: '请输入身高', trigger: 'blur' }
        ],
      },
      uid: "",
      dialogVisible: false,
      /*
      *
      * @params isEdit 0: 新增 1: 编辑
      * */
      isEdit: 0
    }
  }

  render() {
    return (
        <div>
         <div className="buttonBar">
           <Button type="primary" style={{"float":"right"}} onClick = {this.addData.bind(this)}>新增</Button>
         </div>
          <div style={{"marginTop": "20px"}}>
            <Table
                style={{width: '100%'}}
                columns={this.state.columns}
                data={this.state.data}
                stripe={true}
                border={true}
            />
          </div>
          <div>
            <Pagination layout="total, prev, pager, next, jumper, sizes" total={this.state.total}
                        pageSizes={[10, 20, 30, 40]} pageSize={10} currentPage={this.state.currentPage}
                        style={{"float": "right", "marginTop": "20px"}} onCurrentChange={this.pageChange.bind(this)}
                        onSizeChange={this.pageSizeChange.bind(this)}/>
          </div>
          <div>
            <Dialog
                title="收货地址"
                visible={ this.state.dialogVisible }
                onCancel={ () => this.setState({ dialogVisible: false }) }
            >
              <Dialog.Body>
                <Form model={this.state.form} rules={this.state.rules} ref="form">
                  <Form.Item label="姓名" labelWidth="120" prop="name">
                    <Input value={this.state.form.name} onChange={this.onChangeInput.bind(this, 'name')}></Input>
                  </Form.Item>
                  <Form.Item label="性别" labelWidth="120" prop="sex">
                    <Select value={this.state.form.sex} placeholder="请选择性别" onChange={this.onChangeInput.bind(this, 'sex')}>
                      <Select.Option label="男" value="1"></Select.Option>
                      <Select.Option label="女" value="2"></Select.Option>
                    </Select>
                  </Form.Item>
                  <Form.Item label="介绍" labelWidth="120" prop="intro">
                    <Input value={this.state.form.intro} onChange={this.onChangeInput.bind(this, 'intro')}></Input>
                  </Form.Item>
                  <Form.Item label="身高" labelWidth="120" prop="stature">
                    <Input value={this.state.form.stature} onChange={this.onChangeInput.bind(this, 'stature')}></Input>
                  </Form.Item>
                </Form>
              </Dialog.Body>
              <Dialog.Footer className="dialog-footer">
                <Button onClick = {() => this.setState({ dialogVisible: false })}>取 消</Button>
                <Button onClick = {this.submitData.bind(this, this.state.uid)}>确 定</Button>
              </Dialog.Footer>
            </Dialog>
          </div>
        </div>
    );
  }

  componentDidUpdate() {
    // console.log(this.state);
  }

  componentWillUpdate() {

  }

  componentDidMount() {
    this.getList();
    // store.dispatch(actions.increase(5));
    // store.dispatch(actions.addlist([1,2,3,4]));
    // console.log(store.getState());
  }

  componentWillUnmount () {
    this.setState = (state,callback)=>{
      return;
    };
  }

  getList() {
    axios.get("http://esjelly.com/student/home/index/studentlist", {
      params: {pageSize: this.state.pageSize, currentPage: this.state.currentPage}
    })
        .then((res) => {
          if (res.data.success == 200) {
            let data = res.data.data;
            data.forEach ((item) => {
              item.sex = this.transFormSex(item.sex);
            });
            this.setState({
              data: data,
              total: res.data.total
            })
          }
        })
        .catch((err) => {
          console.log(err);
        })
  }

  addData() {
    // let obj = {
    //   id: '2018-05-07',
    //   name: '小明',
    //   sex: '哈哈哈'
    // };
    // let data = [...this.state.data];
    //
    // data.push(obj);
    // setTimeout(() => {
    //   this.setState({
    //     data: data
    //   });
    //   console.log(this.state);
    // },0)

    // this.setState({
    //   data: data
    // }, () => {
    //   console.log(this.state);
    //   console.log('data更新');
    // });

    // Message('这是一条消息提示');

    Notification({
      title: '标题名称',
      message: '这是提示文案这是提示文案这是提示文案这是提示文案这是提示文案这是提示文案这是提示文案这是提示文案',
      duration: 0
    });
    // this.setState({
    //   count: this.state.count + 1
    // });
    // console.log(this.state.count);
    // this.setState({
    //   count: this.state.count + 1
    // });
    // console.log(this.state.count);
    // setTimeout(() => {
    //   this.setState({count: this.state.count + 1});
    //   console.log(this.state.count);  // 第 3 次 log->2
    //
    //   this.setState({count: this.state.count + 1});
    //   console.log(this.state.count);  // 第 4 次 log->3
    // }, 0);


  }

  pageChange(currentPage) {
    this.setState({currentPage}, () => {
      this.getList();
    });
  }

  pageSizeChange(pageSize) {
    this.setState({pageSize}, () => {
      this.getList();
    });
  }

  onRateChange(rate) {
    alert(rate);
  }

  handleChange(key, value) {
    // this.setState({ [key]: value });

    console.log(value);
  }

  /**
   * 时间戳格式化函数
   * @param  {string} format    格式
   * @param  {int}    timestamp 要格式化的时间 默认为当前时间
   * @return {string}           格式化的时间字符串
   */

  formatDate (now) {
    var d = new Date(parseInt(now));
    var year=d.getFullYear();
    var month=d.getMonth()+1;
    var date=d.getDate();
    var hour=d.getHours()<10? "0" + d.getHours() : d.getHours();
    var minute=d.getMinutes()<10? "0" + d.getMinutes() : d.getMinutes();
    var second=d.getSeconds()<10? "0" + d.getSeconds() : d.getSeconds();
    return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
  }

  delData (row) {
    this.setState({
      uid: row.id
    },() => {
      MessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        this.delDataApi(this.state.uid)
            .then((res) => {
              if (res.status == 200) {
                this.getList();
                Message({
                  type: 'success',
                  message: `${res.msg}`
                });
              } else {
                Message({
                  type: 'error',
                  message: `${res}`
                });
              }
            })
            .catch (err => {
              alert(err);
            })
      }).catch(() => {
        Message({
          type: 'info',
          message: '已取消删除'
        });
      });
    })

  }

  delDataApi (uid) {
    return  axios.post("http://esjelly.com/student/home/index/studentdel", {
      id: uid
    },{
      transformRequest: [function (data) {
        let ret = ''
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret
      }]
    })
        .then((res) => {
          return res.data;
        })
        .catch((err) => {
          return err;
        })
  }

  editData (row) {
    this.setState({
      dialogVisible: true,
      isEdit: 1,
      form: {
        name: row.name,
        sex: this.reverseTransFormSex(row.sex),
        intro: row.intro,
        stature: row.stature
      },
      uid: row.id
    })
  }

  submitData (uid) {
    if (this.state.isEdit === 1) {
      this.refs.form.validate((valid) => {
        if (valid) {
          axios.post("http://esjelly.com/student/home/index/updateStudent", {
            id: uid,
            name: this.state.form.name,
            sex: this.state.form.sex,
            intro: this.state.form.intro,
            stature: this.state.form.stature,
          },{
            transformRequest: [function (data) {
              let ret = ''
              for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
              }
              return ret
            }]
          })
              .then((res) => {
                if (res.data.code == 200) {
                  this.getList();
                  Message({
                    message: '修改成功',
                    type: 'success'
                  });
                  this.setState({
                    dialogVisible: false
                  })
                }
              })
              .catch((err) => {
                console.log(err);
              })
        } else {
          alert('信息不完善');
          return false;
        }
      });
    } else {
      this.refs.form.validate((valid) => {
        if (valid) {
          axios.post("http://esjelly.com/student/home/index/addStudent", {
            id: uid,
            name: this.state.form.name,
            sex: this.state.form.sex,
            intro: this.state.form.intro,
            stature: this.state.form.stature,
          },{
            transformRequest: [function (data) {
              let ret = ''
              for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
              }
              return ret
            }]
          })
              .then((res) => {
                if (res.data.code == 200) {
                  Message({
                    message: '新增成功',
                    type: 'success'
                  });
                  this.getList();
                  this.setState({
                    dialogVisible: false
                  })
                }
              })
              .catch((err) => {
                console.log(err);
              })
        } else {
          alert('信息不完善');
          return false;
        }
      });
    }


  }

  addData () {
    this.refs.form.resetFields();
    this.setState({
      dialogVisible: true,
      isEdit: 0
    })
  }

  onChangeInput (key, value) {
    this.state.form[key] = value;
    this.forceUpdate();
  }


  transFormSex (sex) {
    switch (sex) {
      case "1":
        return "男";
      case "2":
        return "女";
      default:
        return "未知";
    }
  }

  reverseTransFormSex (sex) {
    switch (sex) {
      case "男":
        return "1";
      case "女":
        return "2";
      default:
        return "未知";
    }
  }

}

export default HomePage;
